﻿
#region 版权声明





//



// 
// 代码开源主要用于解决大家在学习和研究协议过程中遇到由于缺乏代码所带来的制约性问题。
// 本代码仅供学习交流使用，大家在使用此开发包前请自行协调好多方面关系，
// 不得用于任何商业用途和非法用途，本人不享受和承担由此产生的任何权利以及任何法律责任。
// 
// 本源代码可通过以下网址获取:
// http://www.vckers.com
//
// Copyright @ 2009-2010  vckers.com.  All Rights Reserved.   
// Framework: 3.5

  

 
//   
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. 
  
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TS.QQ.Threading
{
    /// <summary>
    /// 利用线程池来异步执行线程
    /// </summary>
    public class ThreadExcutor
    {
        /// <summary>提交一个线程等待执行
    /// </summary>
        /// <param name="callable">The callable.</param>
        /// <param name="state">The state.</param>
        public static void Submit(ICallable callable, object state)
        {
            if (!callable.IsRunning)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(callable.Call), state);
            }
        }
        /// <summary>
        /// 注册一个轮循线程
    /// </summary>
        /// <param name="runnable">The runnable.</param>
        /// <param name="state">The state.</param>
        /// <param name="interval">The interval.</param>
        public static void RegisterIntervalObject(IRunable runnable, object state, long interval, bool onlyOnce)
        {
            // if (runnable.RegisterdHandler == null)
            // {
            runnable.WaitHandler = new AutoResetEvent(false);
            runnable.RegisterdHandler = ThreadPool.RegisterWaitForSingleObject(runnable.WaitHandler, new WaitOrTimerCallback(runnable.Run), state, interval, onlyOnce);
            // }
        }

        /// <summary>注销轮循线程
        /// Uns the register intervalu object.
        /// </summary>
        /// <param name="runnable">The runnable.</param>
        public static void UnRegisterIntervaluObject(IRunable runnable)
        {
            if (runnable.RegisterdHandler != null && runnable.WaitHandler != null)
            {
                runnable.RegisterdHandler.Unregister(runnable.WaitHandler);
            }
        }
    }
}
